<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Exception\BusinessException;
use App\Service\UserService;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;


#[Controller(prefix: "/admin/auth")]
class AuthController extends AbstractController
{
    #[Inject]
    protected UserService $userService;

    /**
     * 管理员登录接口
     * @param RequestInterface $request
     * @return array|ResponseInterface
     */
    #[PostMapping("login")]
    public function login(RequestInterface $request): array|ResponseInterface
    {
        // 解析参数
        $params = $this->parseParams($request);

        // 验证参数
        if (!isset($params['email']) || !isset($params['password'])) {
            return $this->fail(40002, "登录失败", ["errors" => "email或密码缺失"]);
        }

        // 获取客户端IP
        $ip = $request->getServerParams()['remote_addr'] ?? '';
        try {
            $ret = $this->userService->login($params['email'], $params["password"], $ip, "admin");// 管理员登录
        } catch (BusinessException $e) {
            return $this->fail(40002, "登录失败", ["errors" => $e->getMessage()]);
        }
        return $this->success($ret, "登录成功");
    }
}
